import { values } from "mobx";
import { types, flow } from "mobx-state-tree";
import { delay } from "../tools/utils";

export const Book = types.model("Book", {
  id: types.identifier,
  name: types.string,
  description: types.string,
  price: types.number,
});

const mockData: any = [
  {
    id: "1",
    name: "十万个为什么",
    description: "为什么为什么为什么为什么为什么为什么",
    price: 66,
  },
  {
    id: "2",
    name: "中国上下五千年",
    description: "五千年五千年五千年五千年五千年五千年五千年五千年五千年",
    price: 23,
  },
  {
    id: "3",
    name: "一千零一夜",
    description: "一千零一夜一千零一夜一千零一夜一千零一夜",
    price: 33,
  },
  {
    id: "4",
    name: "昆虫记",
    description: "🐸🐌🐛🦗🐜🐝🐞🦂🕷🦋",
    price: 200,
  },
];

export const BooksModel = types
  .model("BooksModel", {
    isLoading: false,
    books: types.map(Book),
  })
  .views((self) => ({
    get BookArr() {
      return values(self.books);
    },
  }))
  .actions((self) => {
    function markLoading(loading: boolean) {
      self.isLoading = loading;
    }

    function updateBooks(data: any) {
      data.forEach((book: any) => {
        self.books.put(book);
      });
    }

    const getSelectBook = (id: string) => {
      return self.books.get(id);
    };

    const asyncLoad = flow(function* () {
      self.isLoading = true;
      yield delay(1000);
      updateBooks(mockData);
      markLoading(false);
    });
    return { updateBooks, asyncLoad, getSelectBook };
  });
